<?php

class PageRevisionController extends BackOfficeController
{
    public $defaultAction = 'admin';
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';
    
    private $_workflows;

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete()
	{
        if (is_array($_GET['id']) && isset($_GET['id']['id'], $_GET['id']['page_id'])) {
            $id = (int) $_GET['id']['id'];
            $pageId = (int) $_GET['id']['page_id'];
            $deleteWidgetData = $_GET['delete_widget_data'];
            
            // delete one or multiple objects given the list of object IDs
            $result = FSM::run('Cms.PageRevision.delete', array(
                'revision' => $id,
                'page_id'=>$pageId,
                'delete_template'=>$this->get('delete_template', false),
                'delete_widget_data'=>$this->get('delete_widget_data', false),
            ));
            if ($result->hasErrors()) {
                echo $result->getError('ErrorCode');
            } elseif(!Yii::app()->request->isAjaxRequest) {
                // only redirect user to the admin page if it is not an AJAX request
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
            }
        } else {
            throw new CHttpException(400,Yii::t('Core','Cannot delete item with the given ID.'));
        }
	}

    /**
     * Manages all models.
     */
    public function actionAdmin($page_id)
    {
        $model=new PageRevision('search');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['PageRevision']))
            $model->attributes=$_GET['PageRevision'];
            
        $model->page_id = (int) $page_id;
        
        $workflows = $this->getWorkflows($page_id, false);
        
        //find inital workflow
        $defaultSiteId = Yii::app()->cmsManager->site['id'];
        $result = FSM::run('Cms.workflow.getInitialWorkflowBySiteId', array('site_id'=>$defaultSiteId));
        $initialWorkflowId = 0;
        if (!$result->hasErrors())
            $initialWorkflowId = $result->model->id;
        if (Yii::app()->request->getQuery('layout', '') === 'popup')
        {
            $cs=Yii::app()->getClientScript();
            $cs->registerScriptFile(Yii::app()->theme->baseUrl.'/scripts/fancybox/jquery.fancybox-1.3.4.pack.js', CClientScript::POS_END);
            $cs->registerCssFile(Yii::app()->theme->baseUrl.'/scripts/fancybox/jquery.fancybox-1.3.4.css');
            $this->render('admin',array(
                'model'=>$model,
                'workflows'=>$workflows,
                'initialWorkflowId'=>$initialWorkflowId,
            ));
        }
        else
        {
            $html = $this->renderPartial('admin',array(
                'model'=>$model,
                'workflows'=>$workflows,
                'initialWorkflowId'=>$initialWorkflowId,
            ), true, true);
            //don't load scripts
            $html = preg_replace('/<link rel="stylesheet" type="text\/css" href="([^"]+)\.css" \/>/', '', $html);
            $html = preg_replace('/<script type="text\/javascript" src="([^"]+)\.js"><\/script>/', '', $html);
            echo $html;
        }
    }

	/**
	 * Manages all models.
	 */
	public function actionWorkflow($page_id)
	{
        $model=new PageRevision('search');
        $model->unsetAttributes();
        if(isset($_GET['PageRevision']))
            $model->attributes=$_GET['PageRevision'];
            
        $model->page_id = (int) $page_id;

        if (Yii::app()->request->getQuery('layout', '') === 'popup')
        {
            Yii::app()->clientScript->registerScriptFile(Yii::app()->theme->baseUrl.'/scripts/fancybox/jquery.fancybox-1.3.4.js');
            Yii::app()->clientScript->registerCssFile(Yii::app()->theme->baseUrl.'/scripts/fancybox/jquery.fancybox-1.3.4.css');
            Yii::app()->clientScript->registerCss('HidePreviewLink', '.actions-column .view {display:none;}');
            $this->render('workflow',array('model'=>$model));
        }
        else
        {
            $html = $this->renderPartial('workflow',array(
                'model'=>$model,
    //            'sites'=>$sites,
            ), true, true);
            //don't load scripts
            $html = preg_replace('/<link rel="stylesheet" type="text\/css" href="([^"]+)\.css" \/>/', '', $html);
            $html = preg_replace('/<script type="text\/javascript" src="([^"]+)\.js"><\/script>/', '', $html);
            echo $html;
        }
	}
    
    /**
    * DEPRECATED 2011-07-06
    * 
    */
    public function actionLog()
    {
        $this->render('log');
    }
    
    public function actionTemplate($revision_id, $page_id)
    {
        if (Yii::app()->request->IsPostRequest) {
            // save posted data
            $_POST['validateOnly'] = ($this->post('ajax','') == 'page-revision-form');
            
            //update position containers
            $str = $this->post('containers','');
            $str = substr($str, 1);
            $str = html_entity_decode($str);            
            $str = urldecode($str);
            parse_str($str, $containers);
            //copy widgets and update page_widget_id in containers
            $_POST['containers'] = $containers;
            
            $result = FSM::run('Cms.PageRevision.updateTemplate', $_POST);
            $model = $result->model;

            if ($this->post('ajax','') == 'page-revision-form'){
                echo $result->getActiveErrorMessages($result->model);
                Yii::app()->end();
            }
                
            //update position containers
            $containers = $result->containers;
            FSM::run('Cms.pageWidget.updateContainers', array(
                'page_id'=>$page_id,
                'revision'=>$revision_id,
                'containers'=>$containers,
            ));
            
            if (! $result->hasErrors())
            {
                $this->message = Yii::t('Core','Item has been saved successfully.');
                if (empty($model->js_files) === false)
                    $model->js_files = @eval('return '.$model->js_files.';');
                if (empty($model->css_files) === false)
                    $model->css_files = @eval('return '.$model->css_files.';');
                $this->refresh();
            }
        }
        else
        {
            $model = FSM::run('Cms.PageRevision.get', array('id' => $revision_id, 'page_id'=>$page_id))->model;
            if (!is_object($model))
                throw new CHttpException(404, 'Invalid page_revision_id');
        }
        
        if (!is_array($model->js_files) || (is_array($model->js_files) && count($model->js_files) <= 0))
            $model->js_files = array('');
        if (!is_array($model->css_files) || (is_array($model->css_files) && count($model->css_files) <= 0))
            $model->css_files = array('');
            
        //content structure
        $page = FSM::run('Cms.page.getPageDetails', array('page_id'=>$page_id, 'revision'=>$revision_id))->model;
        //find all containers of page
        $containers = array();
        if (is_array($page->revisions) && count($page->revisions))
        {
            if (is_object($page->revisions[0]->templateContent))
            {
                $result = FSM::run('Cms.templateContent.findAllContainters', array(
                    'id'=>$page->revisions[0]->templateContent->id,
                    'recursive'=>true,
                    'include_layout'=>true
                ));
                if (! $result->hasErrors())
                {
                    $containers = $result->containers;                    
                }
            }
        }
        
        $pageWidgets = $page->pageWidgets;
        
        foreach ($pageWidgets as $item)
        {
            $name = is_object($item->widget) ? $item->widget->name.' - '.$item->id : $item->widget_id;
            //find url update
            $params = array();
            if (is_string($item->widget_settings))
                $params = $this->evaluateExpression($item->widget_settings);
            if (is_array($params))
            {
                if (isset($params['widget']))
                {
                    if (!isset($params['widget']['criteria']))
                        $params = $params['widget'];
                }
            }
            else
                $params = array();
            $params['page_widget_id'] = $item->id;
            array_unshift($params, '/'.trim($item->widget->path,'/').'/update');
            $name = CHtml::link($name,$params, array('class'=>'widget-title'));
            //show template info for widgets of template
            if ($item->widget_settings_id)
            {
                $name = '<span class="disable-delete">'.$name;
                $pwModel = PageWidget::model()->findByPk($item->widget_settings_id);
                if (is_object($pwModel))
                {
                    $tplModel = TemplateContent::model()->with(array('template'))->findByPk($pwModel->template_content_id);
                    if (is_object($tplModel))
                        $name .= '('.$tplModel->template->name.' #r'.$tplModel->revision_id.')';
                }
                $name .= '</span>';
            }
            if (isset($containers[$item->container]))
            {
                $containers[$item->container]['items_'.$item->id] = $name;
            }
            else
            {
                $containers[$item->container] = array('items_'.$item->id=>$name);
            }
        }
        
        $this->render('template',array(
            'model'=>$model,
            'containers'=>$containers,
            'pageId'=>$page_id,
            'revision'=>$revision_id,
        ));
    }
    
    protected function getWorkflows($pageId, $useUrl=true)
    {
        if ($this->_workflows === null)
        {
            $workflows = array();
            $page = FSM::run('Cms.page.get', array('id'=>$pageId))->model;
            if (is_object($page))
            {
                $models = FSM::run('Cms.workflow.getBySite', array('site_id'=>$page->site_id))->models;
                if (is_array($models) && count($models))
                {
                    foreach ($models as $workflow)
                    {
                        if ($useUrl)
                            $workflows[$workflow->url] = 'In '.$workflow->name;
                        else
                            $workflows[$workflow->id] = $workflow->name;
                    }
                }
            }
            $this->_workflows = $workflows;
        }
        return $this->_workflows;
    }
    
    protected function getWorkflowName($pageId, $id)
    {
        static $init;
        if (!isset($init))
        {
            $init = true;
            $this->_workflows = null;
        }
        $workflows = $this->getWorkflows($pageId, false);
        Yii::trace('$workflows '.CVarDumper::dumpAsString($workflows));
        if (isset($workflows[$id]))
            return $this->_workflows[$id];
        return '';
    }
    
    protected function getWorkflowUrl($id)
    {
        $model = Workflow::model()->findByPk($id);
        if (is_object($model))
            return $model->url;
        return '';
    }
    
    protected function renderActiveWorkflow($data)
    {
        if (is_array($data) && count($data))
        {
            $count = 0;
            foreach ($data as $id => $name)
            {
                if ($count > 0)
                    echo ', ';
                $count++;
                echo CHtml::tag('span', array('id'=>'workflow-'.$id), CHtml::encode($name));
            }
        }
    }
    
    public function actionEditLog()
    {
        $revisionId = $this->get('revision_id', 0);
        $pageId = $this->get('page_id', 0);
        $data = $this->post('data', '');
        
        $criteria = new CDbCriteria();
        $criteria->compare('id', $revisionId);
        $criteria->compare('page_id', $pageId);
        PageRevision::model()->updateAll(array(
            'log'=>$data,
            'last_update'=>date('Y-m-d H:i:s'),
        ), $criteria);
    }
}